import PageContainer from '@/components/PageContainer';
import type { IUserMessageItem } from '@/models/messages';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import { View, Text, Image } from '@tarojs/components';
import { useRouter } from '@tarojs/taro';
import { FC, Fragment, useCallback, useEffect, useMemo, useReducer } from 'react';
import moment from 'moment';
import type { Moment } from 'moment';
import { Phone, Comment, Wechat } from '@taroify/icons';
import { Checkbox } from '@taroify/core';
import { useMessagesStore } from '@/hooks';
import messageModel from '@/models/messages';
import i18n from 'i18n-js';
import Alert from '@/components/Alert';
import Toast from '@/utils/Toast';
import { observer } from 'mobx-react-lite';
import { GButton } from '@/components/GButton';
import AreaScrollView from '@/components/AreaScrollView';
import TypePicker from '../components/TypePicker';
import { TypePickerOptionEnum } from '../utils'
import NotiTypeText from '../components/NotiTypeText';
import { handleMessageStatus } from '@/services/messages';

const showNotiType = [0, 1, 2, 3, 5];

const appsOutlined = 'https://xbgroup-static.gizwits.com/cybertron/users/495101/media/icon_batch@3x_1695205973131.png';
const appIcon =
  'https://xbgroup-static.gizwits.com/cybertron/users/495101/media/message_icon_wechat%E5%A4%87%E4%BB%BD@3x_1695119174343.png';
const systemIcon =
  'https://xbgroup-static.gizwits.com/cybertron/users/495101/media/message_icon_wechat@3x_1695119174341.png';
const wechatNotiIcon = 'https://xbgroup-static.gizwits.com/cybertron/users/375869/media/message_icon_wechat@3x_1695367811573.png';

interface ITimeData {
  [propname: string]: IUserMessageItem[];
}
const merageDataTime = (data: IUserMessageItem[]) => {
  // 根据时间聚合
  const timeData: ITimeData = {};
  let arr = data.filter(i => showNotiType.findIndex(t => t === i.type) > -1);

  arr.map(item => {
    const dayString = moment(item.ctime).format('YYYY-MM-DD');
    if (!timeData[dayString]) {
      timeData[dayString] = [];
    }
    timeData[dayString].push(item);
  });
  return timeData;
};

const dstyles = GStyleSheet.create({
  container: {
    flex: 1,
    height: '100%',
    backgroundColor: DynamicColors.screenBackgroundGaryColor,
    display: 'flex',
    flexDirection: 'column',
  },
  header: {
    marginTop: 10,
    justifyContent: 'space-between',
    paddingLeft: 20,
    paddingRight: 15,
    height: 40,
  },
  notiContentTips: {
    fontSize: 13,
    color: '#333',
    marginLeft: 5,
  },
  notiContentTime: {
    fontSize: 13,
    color: DynamicColors.normalTextGaryColor,
  },
  errorTips: {
    color: '#e80037',
  },
  notiContentTitle: {
    padding: '0 4rpx',
  },
  notiContent: {
    display: 'flex',
    alignItems: 'center',
    color: '#696969',
    fontSize: 13,
    marginLeft: 10,
  },
  itemCheckBox: {
    position: 'absolute',
    right: 17,
    top: 20,
  },
  wxItemTipsContainer: {
    margin: '14rpx 0',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'flex-start',
    marginLeft: 10,
  },
  itemTips: {
    color: '#696969',
    fontSize: 13,
    margin: '14rpx 0',
    marginLeft: 10,
  },
  item: {
    backgroundColor: '#fff',
    display: 'flex',
    flexDirection: 'row',
    padding: '40rpx 30rpx',
    margin: '20rpx 0',
    position: 'relative',
  },
  checkBox: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkText: {
    marginRight: '10rpx',
  },
  timeBox: {
    display: 'flex',
    flexDirection: 'row',
    padding: '0 40rpx',
  },
  optionBox: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-end',
    padding: '4rpx 40rpx',
  },
  timeTips: {
    position: 'relative',
    marginTop: '18rpx',
    marginLeft: '4rpx',
    color: '#717171',
    fontSize: '26rpx',
  },
  timeTitle: {
    fontSize: '46rpx',
    color: '#000',
    fontWeight: 'bold',
  },
  list: {
    padding: '20rpx 0 0 0',
  },
  itemTitle: {
    fontSize: 18,
  },
  itemContent: {
    display: 'flex',
    flexDirection: 'column',
    flex: 1,
    paddingRight: 10,
  },
  itemRedPoint: {
    width: 8,
    height: 8,
    borderRadius: 8,
    backgroundColor: '#e80037',
    position: 'absolute',
    right: 20,
    top: 25,
  },
  deleteButton: {
    width: '40%',
    margin: 0,
    borderRadius: 24,
    borderColor: DynamicColors.deleteButton,
  },
  btnView: {
    padding: 20,
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
});

interface DeviceNotiState {
  edit: boolean;
  selectData: number[];
  type: TypePickerOptionEnum;
  delShow: boolean;
}

const initialState: DeviceNotiState = {
  edit: false,
  selectData: [],
  type: TypePickerOptionEnum.all,
  delShow: false,
};

const DeviceNotification: FC<{}> = () => {
  const style = dstyles.useDynamicStyle();
  const { editDeviceMessages } = useMessagesStore();
  const {
    params: { deviceName, mac: dMac, productKey: dPk },
  } = useRouter<{ deviceName: string; mac: string; productKey: string }>();
  const [state, dispatch] = useReducer(
    (notiState: DeviceNotiState, action: Partial<DeviceNotiState>) => ({ ...notiState, ...action }),
    { ...initialState }
  );
  const { edit, selectData, type, delShow } = state;

  const data = useMemo(() => {
    const d = editDeviceMessages.content;
    switch (type) {
      case TypePickerOptionEnum.all:
        return d;
      default:
        return d.filter(i => i.msgType == type);
    }
  }, [editDeviceMessages.content, type]);

  const pageTitle = useMemo(() => deviceName ?? '', [deviceName]);
  const allData = useMemo(() => data.map(i => i.id), [data]);
  const isFullCheck = useMemo(() => allData.sort().toString() === selectData.sort().toString(), [allData, selectData]);
  console.log('allDataallData',allData, selectData)
  const handleCheckboxChange = () => {
    dispatch({ selectData: isFullCheck ? [] : [...allData] });
  };

  const handleTypeChange = (pType: TypePickerOptionEnum) => {
    dispatch({ type: pType });
  };

  const onCancel = useCallback(() => {
    dispatch({ edit: false });
  }, []);

  const onDelete = useCallback(() => {
    dispatch({ delShow: true });
  }, []);

  const hideDelAlert = useCallback(() => {
    dispatch({ delShow: false });
  }, []);

  const deleteDataHandler = useCallback(async (ids: number[]) => {
    const res = await messageModel.deleteUserMessages(ids);
    dispatch({ delShow: false, edit: false });
    if (res.success) {
      await messageModel.setPartEditDeviceMessages({ productKey: dPk, mac: dMac });
    }
    if (!res.success) {
      Toast.error(i18n.t('DELETE_FAILED'));
    }
  }, [dPk, dMac]);

  const onDelClick = useCallback(() => {
    // 执行删除
    deleteDataHandler(selectData);
  }, [selectData, deleteDataHandler]);

  const onSelect = useCallback(
    (id: number) => {
      const index = selectData.findIndex(sid => sid === id);
      if (index === -1) {
        selectData.push(id);
      } else {
        // 删除
        selectData.splice(index, 1);
      }
      dispatch({ selectData: [...selectData] });
    },
    [selectData, dispatch]
  );

  return (
    <PageContainer title={pageTitle}>
      <View style={style.container}>
        <View style={style.header} className='centerFlex'>
          <TypePicker onChange={handleTypeChange} type={type} />
          {edit ? (
            <View style={style.checkBox}>
              <Text style={style.checkText}>{isFullCheck ? i18n.t('SELECT_ALL_INVERSE') : i18n.t('SELECT_ALL')}</Text>
              <Checkbox checked={isFullCheck} onChange={handleCheckboxChange} />
            </View>
          ) : (
            <Image
              src={appsOutlined}
              style={{ width: 20, height: 20 }}
              onClick={() => {
                dispatch({ edit: true });
              }}
            />
          )}
        </View>

        <View style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
          <List data={data} id='message-device-list' onSelect={onSelect} selectData={selectData} edit={edit} />
          {edit && (
            <View style={style.btnView}>
              <GButton
                onPress={onCancel}
                style={{ ...style.deleteButton, borderColor: '#000' }}
                textStyle={{ color: '#000' }}
                text={i18n.t('CANCEL')}
                primary
              />
              <GButton
                onPress={onDelete}
                disabled={selectData.length === 0}
                style={style.deleteButton}
                textStyle={{ color: DynamicColors.deleteButton.value }}
                text={i18n.t('DELETE_MESSAGE')}
                primary
              />
            </View>
          )}
        </View>
      </View>
      <Alert
        title={i18n.t('TIP')}
        subTitle={i18n.t('SURE_DELETE_MESSAGE')}
        subTitleStyle={{ fontSize: 16 }}
        visible={delShow}
        onCancel={hideDelAlert}
        onConfirm={onDelClick}
      />
    </PageContainer>
  );
};

const List = ({
  id,
  data,
  onSelect,
  selectData,
  edit,
}: {
  id: string;
  data: IUserMessageItem[];
  onSelect: any;
  selectData: number[];
  edit: boolean;
}) => {
  const style = dstyles.useDynamicStyle();

  const realData = merageDataTime(data);
  return (
    <AreaScrollView style={style.list} id={id} containerStyle={{ height: '90%' }}>
      {Object.values(realData).map(item => {
        const timeData = moment(item[0].ctime);
        return (
          <View key={timeData.format('YYYY-MM-DD')}>
            <View style={style.timeBox}>
              <Text style={style.timeTitle}>{timeData.format('DD')}</Text>
              <Text style={style.timeTips}>
                {timeData.format('MM')}
                {i18n.t('MOUNT')}
              </Text>
            </View>
            {item.map(subItem => {
              const target = selectData.includes(subItem.id);
              return <Item edit={edit} selected={!!target} onSelect={onSelect} data={subItem} />;
            })}
          </View>
        );
      })}
    </AreaScrollView>
  );
};

const Item = ({
  data,
  selected,
  onSelect,
  edit,
}: {
  data: IUserMessageItem;
  onSelect: any;
  selected: boolean;
  edit: boolean;
}) => {
  const style = dstyles.useDynamicStyle();

  const getIcon = ({ result, type, ctime }) => {
    let icon: any = null;
    let text: any = '';
    let tips: any = null;
    switch (type) {
      case 0:
        text = 'APPLICATION_NOTI';
        icon = <Image src={appIcon} style={{ height: 18, width: 18 }} />;
        break;
      case 1:
        text = 'SEND_SMS';
        icon = <Comment size={18} color='#006df9' />;
        break;
      case 2:
        text = 'SYSTEM_NOTI';
        icon = <Image src={systemIcon} style={{ height: 18, width: 18 }} />;
        break;
      case 3:
        text = 'CALL_PHONE';
        icon = <Phone size={18} color='#00c32c' />;
        break;
      case 5:
        text = 'WECHAT_NOTIIFY';
        icon = <Image src={wechatNotiIcon} style={{ height: 18, width: 18 }} />;
        break;
      default:
        break;
    }
    const time = (ctime as Moment).format('HH:mm');
    switch (result) {
      case 0:
        tips = <Text style={style.notiContentTips}>{i18n.t('PUSHED')}</Text>;
        break;
      case 1:
        tips = <Text style={style.notiContentTips}>{i18n.t('SEND_SUCCESS')}</Text>;
        break;
      case 2:
        tips = <Text style={{ ...style.notiContentTips, ...style.errorTips }}>{i18n.t('SEND_FAILED')}</Text>;
        break;
      case 3:
        tips = <Text style={{ ...style.notiContentTips, ...style.errorTips }}>{i18n.t('NO_ANSWER')}</Text>;
        break;
      case 4:
        tips = <Text style={style.notiContentTips}>{i18n.t('HAS_ANSWER')}</Text>;
        break;
      case 5:
        tips = <Text style={{ ...style.notiContentTips, ...style.errorTips }}>{i18n.t('NOTI_FAILED')}</Text>;
        break;
      case 6:
        tips = <Text style={style.notiContentTips}>{i18n.t('NOTI_SUCCESS')}</Text>;
        break;
      default:
        break;
    }
    return (
      <View style={style.notiContent}>
        {icon}
        <Text style={style.notiContentTitle}>{i18n.t(text)}</Text>
        <View style={{ flex: 1 }}>{(data.type == 1 || data.type == 3) && <Text>{data.consumer ?? ''}</Text>}</View>
        <View>
          <Text style={style.notiContentTime}>{time}</Text>
          {tips}
        </View>
        {edit && (
          <Checkbox
            style={style.itemCheckBox}
            checked={selected}
            onChange={() => {
              onSelect(data.id);
            }}
          />
        )}
      </View>
    );
  };

  const getContent = (contentData: IUserMessageItem) => {
    const { msgContent, type } = contentData;
    if (type === 5) {
      const messageContent = JSON.parse(msgContent);
      return (
        <View style={style.wxItemTipsContainer}>
          {messageContent &&
            Object.keys(messageContent).map(title => {
              // if (title !== '提示说明') {
              //   return (
              //     <Text key={title} style={{ fontSize: 13, color: '#696969' }}>
              //       {title}：{messageContent[title]}
              //     </Text>
              //   );
              // }
              // return <Fragment key={title} />;
              return (
                <Text key={title} style={{ fontSize: 13, color: '#696969' }}>
                  {title}：{messageContent[title]}
                </Text>
              );
            })}
        </View>
      );
    } else {
      return <Text style={style.itemTips}>{msgContent}</Text>;
    }
  };

  return (
    <View style={style.item}>
      {edit === false && data.read === false && <View style={style.itemRedPoint} />}
      <View style={style.itemContent}>
        <View>
          <Text style={style.itemTitle}>
            <NotiTypeText msgType={data.msgType} />
            <Text>{data.title}</Text>
          </Text>
        </View>
        {getContent(data)}
        {getIcon(data)}
      </View>
    </View>
  );
};

export default observer(DeviceNotification);
